using NLog;
using NLog.Extensions.Logging;
using Quartz;
using WorkerService.App1.Jobs;
using WorkerService.App1.Workers;

var host = Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureHostConfiguration(configHost =>
    {
        configHost.AddJsonFile("hostsettings.json", optional: true);
        configHost.AddEnvironmentVariables(prefix: "PREFIX_");
        configHost.AddCommandLine(args);
    })
    .ConfigureServices((hostContext, services) =>
    {
        // services.AddHostedService<Worker>();
        // services.AddHostedService<Work2>();
        // services.AddHostedService<HttpWorker>();
        // services.AddHttpClient<HttpWorker>();

        services.AddQuartz(configurator =>
        {
            configurator.UseMicrosoftDependencyInjectionJobFactory();
            // 方式 1
            // var jobKey = new JobKey("HelloJob");
            // configurator.AddJob<HelloJob>(options => options.WithIdentity(jobKey));
            // configurator.AddTrigger(options =>
            // {
            //     options.ForJob(jobKey)
            //         .WithIdentity("JobTrigger")
            //         .WithCronSchedule("0/5 * * * * ?");
            // });
            configurator.AddJobAndTrigger<HelloJob>(hostContext.Configuration);
        });
        services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
    })
    .ConfigureLogging(logger =>
    {
        logger.ClearProviders();
        logger.AddNLog();
    })
    .Build();

await host.RunAsync();

public static class ServiceCollectionQuartzConfiguratorExtensions
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    public static void AddJobAndTrigger<T>(
        this IServiceCollectionQuartzConfigurator quartz,
        IConfiguration config)
        where T : IJob
    {
        // Use the name of the IJob as the appsettings.json key
        var jobName = typeof(T).Name;
        _logger.Info($"jobName: {jobName}");
        // Try and load the schedule from configuration
        var configKey = $"Quartz:{jobName}";
        var cronSchedule = config[configKey];

        if (string.IsNullOrEmpty(cronSchedule))
        {
            throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
        }

        // register the job as before
        var jobKey = new JobKey(jobName);
        quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

        quartz.AddTrigger(opts => opts
            .ForJob(jobKey)
            .WithIdentity(jobName + "-trigger")
            .WithCronSchedule(cronSchedule)); // use the schedule from configuration
    }
}